<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Sms;
use App\Models\Notice\SmsRecord;
use App\Models\Notice\SmsError;
use Illuminate\Support\Facades\Config;

class CheckSms extends Command
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sms:check';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'check the sms send code';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $startTime = date('Y-m-d H:i:s', time() - 7200);
        $endTime = date('Y-m-d H:i:s', time() - 3600);
        $queryTime = date('Ymd');
        $accessKeyId = Config::get('system.sms_access_key_id');
        $accessKeySecret = Config::get('system.sms_access_key_secret');
        
        $smsResult = SmsRecord::where('status', '=', 0)->whereBetween('created_at', [$startTime, $endTime])->get(['phone', 'status', 'biz_id']);
        if (count($smsResult) > 0) {
            foreach ($smsResult as $val) {
                $smsRecord = new SmsRecord();
                $smsRecord = $val;
                $phone = $smsRecord->phone;
                $biz_id = $smsRecord->biz_id;
                $result = Sms::querySendDetails($phone, $biz_id, $queryTime, $accessKeyId, $accessKeySecret);
                if ($result->Code == 'OK') {
                    $res = $result->SmsSendDetailDTOs->SmsSendDetailDTO;
                    $sendStatus = $res[0]->SendStatus;
                    if ($sendStatus == 3) {
                        $smsRecord->status = 1;
                        $smsRecord->save();
                    } else {
                        $smsRecord->status = 2;
                        if ($smsRecord->save()) {
                            $smsError = new SmsError();
                            $smsError->error_code = $res[0]->ErrCode;
                            $smsError->record_id = $smsRecord->id;
                            $smsError->save();
                        }
                    }
                }
            }
        }
    }

}
